package com.yc.testThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 测试线程死循环
 * 主线程会先死掉，另外起的线程则会一直执行下去
 * @author Administrator
 *
 */
public class TestThread2 {
	public void createBusyThread() {
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < 5000; i++) {
					System.out.println("-----"+i);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				
//				while (true)
//					;
				
			}
		}, "testBusyThread");
		thread.start();
		try {
			thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("----------over--");
	}
	
	
	/**
	 * 测试线程休眠、等待【线程死掉是整个线程就断掉了】
	 * @param lock
	 */
	public static void createLockThread(final Object lock){
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (int i = 0; i < 30; i++) {
					try {
						System.out.println("---"+i);
						Thread.sleep(1000);//可监控到线程是休眠状态
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("开始阻塞");
				synchronized (lock) {
					try{
						lock.wait();//可监控到线程是等待状态
					} catch(InterruptedException e) {
						e.printStackTrace();
					}
				}
				
			}
		}, "testLockTread");
		thread.start();
	}
	
	/**
	 * 测试线程死锁
	 * 原理：Integer对 -128 ~ 127内的会缓存起来，返回同一个对象
	 * @author Administrator
	 *
	 */
	static class SynAddRunable implements Runnable {

		int a, b;
		public SynAddRunable(int a, int b) {
			this.a = a;
			this.b = b;
		}
		@Override
		public void run() {
			synchronized (Integer.valueOf(a)) {
				synchronized (Integer.valueOf(b)) {
					System.out.println(a + b);
				}
			}
			
		}
		
	}
	

	public static void main(String[] args) throws IOException {
//		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//		br.readLine();
		TestThread2 t = new TestThread2();
		t.createBusyThread();
//		br.readLine();
//		Object obj = new Object();
//		createLockThread(obj);

//		for (int i = 0; i < 200; i++) {
//			new Thread(new SynAddRunable(1, 2)).start();
//			new Thread(new SynAddRunable(2, 1)).start();
//		}
	}

}
